﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace RoboZip
{
    public class Program
    {
        static AppSettingsReader configuration = new AppSettingsReader();
        static RoboZipCore roboZipCore;
        static Object lockThis = new Object();

        static void Main(string[] args)
        {
            try
            {
                SingletonController.SetPortNumber((int)configuration.GetValue("IPPortNumber", typeof(int)));
                if (SingletonController.StartSingleInstance(new SingletonController.ReceiveDelegate(HandleArguments)))
                {
                    roboZipCore = new RoboZipCore();
                    HandleArguments(args);
                }
                else
                {
                    SingletonController.Send(args);
                }
                SingletonController.Cleanup(HandleArguments);
            }
            catch (Exception ex)
            {
                // ToDo: Log errors to log4net.                
                // Possible Exception: Socket Exception because of already use port.
                Console.WriteLine("Error...");
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }

        static void HandleArguments(string[] args)
        {
            lock (lockThis)
            {
                roboZipCore.CreateJob(args);
            }
        }
    }

}
